package cheme.ProcessEditor.Parts.Equations;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editpolicies.DirectEditPolicy;
import org.eclipse.gef.requests.DirectEditRequest;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.TextCellEditor;

import cheme.ProcessEditor.Parts.ITextModelPart;
import cheme.ProcessModel.IChild;
import cheme.ProcessModel.IModelElement;
import cheme.ProcessModel.Cmds.ReplaceCmd;
import cheme.ProcessModel.Equations.EquationField;

public class PolicyEquationFieldDirectEdit extends DirectEditPolicy
{
	private String oldValue;

	/**
	 * @see DirectEditPolicy#getDirectEditCommand(org.eclipse.gef.requests.DirectEditRequest)
	 */
	protected Command getDirectEditCommand(DirectEditRequest request)
	{
		EquationField model = (EquationField) getHost().getModel();
		TextCellEditor cellEditor = (TextCellEditor)request.getCellEditor();
		
		return  new ReplaceCmd(model, tokenize((String)cellEditor.getValue()));
	}
	
	private List<IChild> tokenize(String source)
	{
		List<IChild> tokenFields = new ArrayList<IChild>();
		String token = "";

		StringTokenizer tokenizer = new StringTokenizer(source, " =\t+-()*^/\\", true); //true entails delimters are returned as tokens
		while(tokenizer.hasMoreTokens())
		{
			token = tokenizer.nextToken();
			
			if(!token.trim().isEmpty())
			{
				EquationField newField = new EquationField(((IModelElement)getHost().getModel()).getParent(), token);
				newField.setToolTipText("Equation token.");
				tokenFields.add(newField);
			}
		}
		
		return tokenFields;
	}

	/**
	 * @see DirectEditPolicy#showCurrentEditValue(org.eclipse.gef.requests.DirectEditRequest)
	 */
	protected void showCurrentEditValue(DirectEditRequest request)
	{
		String value = (String) request.getCellEditor().getValue();
		ITextModelPart part = (ITextModelPart)getHost();
		part.handleTextChange(value);
	}

	/**
	 * @param to Revert request
	 */
	protected void storeOldEditValue(DirectEditRequest request)
	{
		CellEditor cellEditor = request.getCellEditor();
		oldValue = (String) cellEditor.getValue();
	}

	/**
	 * @param request
	 */
	protected void revertOldEditValue(DirectEditRequest request)
	{
//		CellEditor cellEditor = request.getCellEditor();
//		cellEditor.setValue(oldValue);
		ITextModelPart part = (ITextModelPart)getHost();
		part.revertTextChange(oldValue);
	}
}
